Best Time to Buy and Sell Stock II ---- LeetCode

来源:互联网 发布:安卓传感器编程 编辑:程序博客网 时间:2024/06/02 06:05

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).

解题思路: 可以连续买卖,但是每次手中只有一手股票,买入当前股票之前必须将上一次股票卖出。

                  最大利润,将所有上涨的区间都累加。

public class Solution {
    public int maxProfit(int[] prices) {
         int max=0;
         int len=prices.length;
         if(len==0||len==1){
        return 0;
         }
    int low=prices[0];
         int profit=0;
         int i=0;
         boolean flag=false;
         while(i<len){
             low=prices[i];
             i++;
        while(i<len&&prices[i]>=prices[i-1]){
                  i++;
                  flag=true;
        }
        if(flag){
                profit=prices[i-1]-low;      
            max=max+profit;
            flag=false;
        }
         }                                           
    return max;
    }
}


0 0
原创粉丝点击