LeetCode:Best Time to Buy and Sell Stock II

来源:互联网 发布:淘宝买笔记本主板 编辑:程序博客网 时间:2024/05/18 01:43

Best Time to Buy and Sell Stock II

 Total Accepted: 49789 Total Submissions: 130095My Submissions

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

Hide Tags
 Array Greedy
方法一:Greedy(贪心算法)【if(a[i]<a[i+1]){num+=a[i+1]-a[i]}】
   
 public int maxProfit(int[] prices) {        int num=0;        for(int i=0;i<prices.length-1;i++){            if(prices[i]<prices[i+1]){                num+=(prices[i+1]-prices[i]);            }        }        return num;    }

方法二:动规思想
    
public int maxProfit(int[] prices) {        int i=0,num=0;        boolean buy=false;        for(;i<prices.length-1;i++){            if(buy&&prices[i]>prices[i+1]){                num+=prices[i];                buy=false;            }            if(!buy&&prices[i]<prices[i+1]){                num-=prices[i];                buy=true;            }        }        if(buy){            num+=prices[i];        }        return num;    }

0 0
原创粉丝点击