您的位置:山东十一选五开奖 > 股票 > Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

2019-10-03 16:11

题目分析

原题链接,登陆 LeetCode 后可用

这道题是假设给定一个数组,这个数组存的是一支股票在每一天的价格。目标是通过买入、卖出股票使得利润最大化。低价买入,高价卖出就能盈利,这道题目又没有限制买入、卖出的次数,所以只要后一天的值比前一天的大,就能获得利润,所以我们就将所有的利润值求和即可。

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Given an example
[2,1,2,0,1], return 2

代码

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        // 以下 for 循环 包含边界条件了
        // if(prices.length == 0 || prices.length == 1) {
            // return 0;
        // }
        for(int i = 0; i < prices.length - 1; i++) {
            if(prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

变形题,题目变成可以进行多次交易,那我们只需要从头到尾遍历一遍,只要当天减去前一天是正的,我们就可以把值加入sum中。

本文由山东十一选五开奖发布于股票,转载请注明出处: Best Time to Buy and Sell Stock II

关键词: